<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 顶部提示区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条区域 -->
      <el-steps :space="200" :active="activeNum - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab标签页 -->
      <el-form
        :model="addGoodsForm"
        :rules="addGoodsRules"
        ref="addGoodsForm"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeNum"
          :tab-position="tabPosition"
          :before-leave="beforeTabLeave"
          @tab-click="changeTab"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight" type="number">
              <el-input v-model="addGoodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number" type="number">
              <el-input v-model="addGoodsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item>
              <el-cascader
                v-model="goodsIdArr"
                :options="goodsCateList"
                :props="props"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals" @change="manyChange">
                <el-checkbox
                  :label="value"
                  v-for="(value, index) in item.attr_vals"
                  :key="index"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture"
              :headers="headers"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 显示图片的弹出框 -->
    <el-dialog title="图片预览" :visible.sync="picDialogVisible" width="50%">
      <img :src="picUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { getGoodsListApi, getParamsApi, addGoodsApi } from "../api/index.js";
export default {
  data: function() {
    return {
      activeNum: "0",
      // 控制tab的位置
      tabPosition: "left",
      // 商品表单数据
      addGoodsForm: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        attrs: [],
        pics: [],
        goods_cat: [],
        goods_introduce: ''
      },
      // 商品表单验证规则
      addGoodsRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ]
      },
      // 商品分类数据
      goodsCateList: [],
      goodsIdArr: [],
      // 级联选择器的props配置
      props: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      // 分类id
      categoryId: 0,
      // 动态参数数据
      manyData: [],
      // 静态属性数据
      onlyData: [],
      // 上传图片
      fileList: [],
      headers: {
        Authorization: sessionStorage.getItem("token")
      },
      // 控制图片预览的弹出框显示与隐藏
      picDialogVisible: false,
      // 图片预览的图片的路径
      picUrl: ''
    };
  },
  created() {
    this.getGoodsList();
  },
  methods: {
    // 获取商品分类数据
    async getGoodsList() {
      const { data: res } = await getGoodsListApi();
      if (res.meta.status !== 200)
        return this.$message.error("商品分类数据获取失败");
      this.goodsCateList = res.data;
      // console.log(res);
    },
    // 级联选择器触发的函数
    handleChange() {
      // 这里只能选择三级分类
      if (this.goodsIdArr.length !== 3) return (this.goodsIdArr = []);
      this.categoryId = this.goodsIdArr[this.goodsIdArr.length - 1];
    },
    // 切换tab标签之前的钩子函数
    beforeTabLeave(activeName, oldActiveName) {
      // 在跳转之前先判断用户是否选择了商品的分类
      if (this.goodsIdArr.length !== 3) {
        this.$message.error("请选择商品分类");
        return false;
      }
    },
    // tab被选中时触发的函数
    async changeTab() {
      // 首先判断tab栏的索引
      if (this.activeNum == 1) {
        // 获取动态参数
        var sel = "many";
        const { data: res } = await getParamsApi(this.categoryId, sel);
        if (res.meta.status !== 200)
          return this.$message.error("动态参数获取失败");
        res.data.forEach(value => {
          value.attr_vals = value.attr_vals.split(",");
        });
        this.manyData = res.data;
        console.log(this.manyData);
      } else if (this.activeNum == 2) {
        // 获取静态属性的数据
        var sel = "only";
        const { data: res } = await getParamsApi(this.categoryId, sel);
        if (res.meta.status !== 200)
          return this.$message.error("静态属性获取失败");
        this.onlyData = res.data;
        // console.log(res);
      }
      console.log(this.activeNum);
    },
    // 商品参数移除的change事件
    manyChange(val) {
      this.manyData.forEach(value => {
        console.log(value.attr_vals);
      });
    },
    handlePreview(file) {
      this.picDialogVisible = true
      this.picUrl = file.response.data.url
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    // 图片上传成功的钩子
    handleSuccess(response) {
      if (response.meta.status !== 200)
        return this.$message.error("图片上传失败");
      this.$message.success("图片上传成功")
      this.addGoodsForm.pics.push({pic: response.data.tmp_path})
      // console.log(response);
    },
    // 添加商品
    async add() {
      this.$refs.addGoodsForm.validate(valid => {
        if(!valid) return
      })
      this.addGoodsForm.goods_cat = this.goodsIdArr
      this.addGoodsForm.goods_cat = this.addGoodsForm.goods_cat.join(',')
      this.manyData.forEach(value => {
        var valueInfo = {attr_id: value.attr_id, attr_value: value.attr_vals.join(',')}
        this.addGoodsForm.attrs.push(valueInfo)
      })
      this.onlyData.forEach(value => {
        var valueInfo = {attr_id: value.attr_id, attr_value: value.attr_vals}
        this.addGoodsForm.attrs.push(valueInfo)
      })
      const {data: res} = await addGoodsApi(this.addGoodsForm)
      if(res.meta.status !== 201) return this.$message.error('商品添加失败')
      this.$message.success('商品添加成功')
      this.$router.push('/goods')
    }
  }
};
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 !important;
  margin-right: 10px !important;
}
.el-dialog img {
  width: 100%;
}
.el-button {
  margin-top: 15px;
}
</style>
